package com.manlost.web.common.download;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.manlost.upload.operate.FTPOp;

/**
 * 
 * @author wqq
 * 
 */
public class HttpDownload {
	private static final Log log = LogFactory.getLog(HttpDownload.class);
	private List<String> downloadUrls = new ArrayList<String>();// URL列表
	private List<FileInfo> files = new ArrayList<FileInfo>();//
	private String basePath;
	private FTPOp ftpOp;

	public String getBasePath() {
		return basePath;
	}

	public void setBasePath(String basePath) {
		this.basePath = basePath;
	}

	public HttpDownload() {
		
	}
	
	public void openFtp(){
		ftpOp=new FTPOp();
		try {
			ftpOp.connectDefaultServer();
		} catch (IOException e) {
			log.error("connect to ftp occours error!",e);
		}
	}

	public void closeFtp(){
		try {
			ftpOp.closeServer();
		} catch (IOException e) {
			log.error("close ftp occours error!",e);
		}
	}
	public List<String> getDownloadUrls() {
		return downloadUrls;
	}

	public void resetList() {
		downloadUrls.clear();
		files.clear();
	}

	public void addItem(String url, FileInfo fileInfo) {
		downloadUrls.add(url);
		files.add(fileInfo);
	}

	/**
	 * 　* 根据列表下载资源 　
	 */
	public void downLoadByList() {
		String url = null;
		FileInfo fileInfo = null;
		// 按列表顺序保存资源
		for (int i = 0; i < downloadUrls.size(); i++) {
			url = (String) downloadUrls.get(i);
			fileInfo =files.get(i);
			try {
				System.out.println("saveFile---"+url);
				saveToFile(url, fileInfo);
			} catch (IOException e) {
				log.error("saveToFile occurs error", e);
			}
		}
	}
	
	
	public void saveToFile(String destUrl, FileInfo fileInfo) throws IOException {
		BufferedInputStream bis = null;
		HttpURLConnection httpUrl = null;
		URL url = null;
		
		// 建立链接
		url = new URL(destUrl);
		System.out.println("openurl---"+url);
		httpUrl = (HttpURLConnection) url.openConnection();
		// 连接指定的资源
		httpUrl.connect();
		System.out.println("httpUrl---"+httpUrl);
		// 获取网络输入流
		bis = new BufferedInputStream(httpUrl.getInputStream());
		
		Iterator<String> it=fileInfo.getDirs().keySet().iterator();
		while(it.hasNext()){
			String path=it.next();
			ftpOp.mkdir(path);
			ftpOp.cd(path);
		}
		ftpOp.upload(bis, fileInfo.getFileName());
		bis.close();
		httpUrl.disconnect();
	}
}